package main

import (
	"fmt"
	"net/http"
	"strings"
	"time"

	"github.com/gorilla/websocket"
)

var UP = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

type MyConn struct {
	conn     *websocket.Conn
	userName string
	iId      time.Time
}

var MyConns []MyConn

// 未登录的，加入群聊推送缓存信息
var NoReadData []string

func sendNoReadData(conn *websocket.Conn) {
	for _, v := range NoReadData {
		conn.WriteMessage(websocket.TextMessage, []byte(v))
	}
}

// 通知加入群聊
func addSend(info MyConn, conn *websocket.Conn) {
	endStr := info.userName + ",加入群聊 " + time.Now().Format("2006-01-02 15:04:05")
	for _, v := range MyConns {
		if info.iId == v.iId {
			continue
		}
		v.conn.WriteMessage(websocket.TextMessage, []byte(endStr))
	}
	// 推送未读消息
	sendNoReadData(conn)
}

// 通知退出群聊
func rmSend(info MyConn, conn *websocket.Conn) {
	endStr := info.userName + ",退出群聊 " + time.Now().Format("2006-01-02 15:04:05")
	for _, v := range MyConns {
		v.conn.WriteMessage(websocket.TextMessage, []byte(endStr))
	}
	// 从群发数组中剔除
	flagIndex := -1
	for i, v := range MyConns {
		if v.iId == info.iId {
			flagIndex = i
			break
		}
	}
	if flagIndex != -1 {
		MyConns = append(MyConns[:flagIndex], MyConns[flagIndex+1:]...)
	}
	// 查看群里还有谁
	for _, v := range MyConns {
		fmt.Printf("%v ", v.userName)
	}
	fmt.Println("还在群内")
}

func handler(w http.ResponseWriter, r *http.Request) {
	// 升级服务为websocket
	conn, err := UP.Upgrade(w, r, nil)
	defer conn.Close()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	// 存入所有的链接
	myIid := time.Now()
	myConn := MyConn{
		conn:     conn,
		userName: strings.Join(r.Header["Username"], ""),
		iId:      myIid,
	}
	MyConns = append(MyConns, myConn)
	// 通知加入群聊
	addSend(myConn, conn)
	// 链接没有断，读取数据
	for {
		_, p, e := conn.ReadMessage()
		if e != nil {
			fmt.Println(e.Error())
			break
		}
		writerStr := myConn.userName + ":" + string(p) + " " + time.Now().Format("2006-01-02 15:04:06")
		// 记录消息
		NoReadData = append(NoReadData, writerStr)
		for _, v := range MyConns {
			if v.iId == myIid {
				continue
			}
			v.conn.WriteMessage(websocket.TextMessage, []byte(writerStr))
		}
		fmt.Println(writerStr)
	}
	rmSend(myConn, conn)
	fmt.Println(myConn.userName + "链接断开...")
}

func main() {
	http.HandleFunc("/", handler)
	fmt.Println("server start :8888")
	http.ListenAndServe(":8888", nil)
}
